package com.yc.vcode.web;

import com.yc.util.Utils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class VcodeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        //return HandlerInterceptor.super.preHandle(request, response, handler);
        String rcode = request.getParameter("vcode");
        String vcode = (String) request.getSession().getAttribute("vcode");

        Long time = (Long) request.getSession().getAttribute("vcode-timeout");
        if (vcode == null) {

            Utils.writeResult(0,"请获取验证码!",null,response);
            return false;
        }

        if (time < System.currentTimeMillis()) {
            Utils.writeResult(0,"验证码过期,请重新获取验证码!",null,response);
            return false;
        }

        if (rcode == null) {

            Utils.writeResult(0,"请输入验证码!",null,response);
            return false;
        }

        if (!rcode.equalsIgnoreCase(vcode)) {
            Utils.writeResult(0,"输入的验证码错误!",null,response);
            return false;
        }

        request.getSession().removeAttribute("vcode");

        return true;
    }
}
